package com.obixlabs.security.credentialsstore.server.serviceimpl;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.obixlabs.security.credentialsstore.exception.EntryNotFoundException;
import com.obixlabs.security.credentialsstore.model.BaseUser;
import com.obixlabs.security.credentialsstore.model.ObixGroup;
import com.obixlabs.security.credentialsstore.model.ObixGroups;
import com.obixlabs.security.credentialsstore.server.dao.GroupDAO;
import com.obixlabs.security.credentialsstore.server.dao.UserDAO;
import com.obixlabs.security.credentialsstore.services.GroupManagementService;

public class GroupManagementServiceDefaultImpl 	extends ConcurrentServiceBase 
												implements GroupManagementService
{	
	private static final Logger logger = 
		LoggerFactory.getLogger(GroupManagementServiceDefaultImpl.class);
	
	private GroupDAO groupDAO;
	private UserDAO userDAO;
	
	public void setGroupDAO(GroupDAO groupDAO) {this.groupDAO = groupDAO;}
	public GroupDAO getGroupDAO() {return groupDAO;}
	
	public UserDAO getUserDAO() {return userDAO;}
	public void setUserDAO(UserDAO userDAO)
	{this.userDAO = userDAO;}
	
	public String getServiceName(){return GroupManagementService.SERVICE_NAME;}
		
	@Override
	public ObixGroup saveGroup(ObixGroup group)
	{
		lockForWrite();
		try
		{						
			if (logger.isDebugEnabled())
				logger.debug("Saving '"+group +"'.");		
			return groupDAO.save(group);
		} finally {unlockAfterWrite();}
	}
	
	@Override
	public void deleteGroup(ObixGroup group)
	{
		lockForWrite();
		try
		{								
			if (logger.isDebugEnabled())
				logger.debug("Deleting '"+ group +"'.");		
			groupDAO.delete(group);
		} finally {unlockAfterWrite();}			
	}
	
	@Override
	public ObixGroups getAllGroups()
	{
		lockForRead();
		try
		{										
			ObixGroups result = groupDAO.findAll();
			if (logger.isDebugEnabled())
				logger.debug("Found '"+ result.size() +"' groups.");		
			return result;
		} finally {unlockAfterRead();}			
	}
	
	@Override
	public ObixGroup getGroup(String groupName)
	{
		lockForRead();
		try
		{										
			ObixGroup result = groupDAO.findByName(groupName);
			if (logger.isDebugEnabled())
				logger.debug("Found '"+ result +"'.");		
			return result;
		} finally {unlockAfterRead();}				
	}
	
	@Override
	public Set<BaseUser> getGroupMembers(ObixGroup group) throws EntryNotFoundException
	{
		lockForRead();
		try
		{												
			Set<BaseUser> result = userDAO.findByGroup(group);
			if (logger.isDebugEnabled())
				logger.debug(result.size() +" total users assigned to group '" + group +"'");		
			return result;
		} finally {unlockAfterRead();}			
	}//end method def	
	
}